//
//  KABCosplayVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosplayVC.h"
#import "UIButton+EdgeInsets.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABCosplayTCell.h"
#import "KABCelebrityTCell.h"
#import "GlobalHeader.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "XDFilterView.h"
#import "KABCosplayPublishVC.h"
#import "KABCosplayDetailVC.h"
#import <UINavigationBar+Awesome.h>
#import "KABHomepageVC.h"
#import "ThemeManager.h"
#import "NSString+XDLink.h"
#import "KABMineColCosVC.h"
#import "KABCosTopicSeaVC.h"
#import <UIScrollView+EmptyDataSet.h>
#import "KABCosUserSeaVC.h"
#import "KABCosAuthenticationVC.h"

typedef NS_ENUM(NSInteger, CosplayViewTyep) {
    CosplayViewTyepWhole = 0,   //!< 全部
    CosplayViewTyepRecommend,   //!< 推荐
    CosplayViewTyepFollow,      //!< 关注
    CosplayViewTypeCelebrity,   //!< 名人榜
};

@interface KABCosplayVC ()<UITableViewDelegate, UITableViewDataSource, KABCosplayTCellDelegate, KABCelebrityTCellDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (assign, nonatomic) CosplayViewTyep viewType;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;
@property (strong, nonatomic) XDFilterView *filterView;
@property (strong, nonatomic) NSArray *titlesArray;
@property (strong, nonatomic) UIBarButtonItem *publishBarBtnItem;

@property (nonatomic, readonly) KABCosplayModel *cosplayList;
@property (nonatomic, readonly) KABCosplayCelebrity *celebrity;
@end

static NSString *const kReuseCosplayCellId = @"KABCosplayTCell";
static NSString *const kReuseCelebrityCellId = @"KABCelebrityTCell";
static NSInteger const kRequestCelebirtySize = 20;
static NSInteger const kRequestCosplayListSize = 10;

@implementation KABCosplayVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"Cosplay";
    self.navigationItem.titleView = [self buttonWithTitle:@"Cosplay"];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cosplay_search"] style:UIBarButtonItemStylePlain target:self action:@selector(searchBarBtnTapped:)];
    self.navigationItem.rightBarButtonItem = self.publishBarBtnItem;
}

- (void)initSubViews {
    UINib *cosplayNib = [UINib nibWithNibName:kReuseCosplayCellId bundle:nil];
    [self.tableView registerNib:cosplayNib forCellReuseIdentifier:kReuseCosplayCellId];
    UINib *celebrityNib = [UINib nibWithNibName:kReuseCelebrityCellId bundle:nil];
    [self.tableView registerNib:celebrityNib forCellReuseIdentifier:kReuseCelebrityCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 90.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 这里是为了避免导航栏出现突兀的情况
    UIColor *navBgColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerNavBgColor];
    [self.navigationController.navigationBar lt_setBackgroundColor:navBgColor];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar lt_reset];
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"什么都没有喔" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - <UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"数量 = %zd", self.celebrity.celebrities.count);
    return (self.viewType == CosplayViewTypeCelebrity) ? self.celebrity.celebrities.count : self.cosplayList.cosplay_list.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.viewType == CosplayViewTypeCelebrity) {
        KABCelebrityTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCelebrityCellId forIndexPath:indexPath];
        if (indexPath.section < self.celebrity.celebrities.count) {
            [cell configViewWithCelebrityItem:self.celebrity.celebrities[indexPath.section]];
        }
        cell.delegate = self;
        return cell;
    } else {
        KABCosplayTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCosplayCellId forIndexPath:indexPath];
        if (indexPath.section < self.cosplayList.cosplay_list.count) {
            KABCosListItem *item = self.cosplayList.cosplay_list[indexPath.section];
            BOOL showPullDown = (item.publisher_id != [KABModel sharedInstance].userInfo.uid);
            [cell configViewWithCosplayItem:item showDeleteBtn:NO showPullDownBtn:showPullDown];
        }
        cell.delegate = self;
        return cell;
    }
}

#pragma mark - <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return (self.viewType == CosplayViewTypeCelebrity) ? 90.0 : 484.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return (self.viewType == CosplayViewTypeCelebrity) ? 0.9 : 5.9;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.viewType == CosplayViewTypeCelebrity) {
        KABCosCelListItem *item = self.celebrity.celebrities[indexPath.section];
        item.isExpanded = !item.isExpanded;
        [tableView beginUpdates];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
        [tableView endUpdates];
    } else {
        KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
        detailVC.cosItem = self.cosplayList.cosplay_list[indexPath.section];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark - <XDFilterViewDelegate>
- (void)xDFilterView:(XDFilterView *)XDFilterView clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.viewType = buttonIndex;
    [self refreshWholeView];
    [self.mj_header beginRefreshing];
}

#pragma mark - KABCosplayTCellDelegate
- (void)kABCosplayTCell:(KABCosplayTCell *)cell portraitImgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = item.publisher_id;
    [self showViewController:vc sender:nil];
}
- (void)kABCosplayTCell:(KABCosplayTCell *)cell pullDownBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"不再显示此内容" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 请求服务器
        [self requestCosShieldWithCosId:item.cosplayId successHandle:^{
            [self.cosplayList removeCosListItem:item];
            // 更新界面
            [self.tableView beginUpdates];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.tableView endUpdates];
        }];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)kABCosplayTCell:(KABCosplayTCell *)cell praiseBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    item.is_praise = !item.is_praise;
    item.is_praise ? ++item.praise : --item.praise;
    
    // 请求服务器
    [self requestCosPraiseWithCosId:item.cosplayId isPraise:item.is_praise];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell commentBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosItem = self.cosplayList.cosplay_list[indexPath.section];
//    detailVC.scrollToComment = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell collectBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    item.is_collected = !item.is_collected;
    
    // 请求服务器
    [self requestCosCollectWithCosId:item.cosplayId isCollected:item.is_collected];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}
- (void)kABCosplayTCell:(KABCosplayTCell *)cell linkTapped:(NSURL *)url {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    
    if ([url isKindOfClass:[NSURL class]]) {
        NSInteger index = [url.absoluteString integerValue];
        NSArray *linkStrArray = item.topContentTopicAndAtUserArray;
        if (index < linkStrArray.count) {
            NSString *linkStr = linkStrArray[index];
            if (linkStr.length <= 2) {
                return;
            }
            if ([linkStr hasPrefix:@"#"]) {
                [self jumpToTopicList:[linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)]];
            } else if([linkStr hasPrefix:@"@"]) {
                [self jumpToAtUserHp:[linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)]];
            }
        }
    }
}
#pragma mark - KABCelebrityTCellDelegate
- (void)kABCelebrityTCell:(KABCelebrityTCell *)cell imgViewDownload:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath) {
        [self.tableView beginUpdates];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }
}
- (void)kABCelebrityTCell:(KABCelebrityTCell *)cell portraitImgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosCelListItem *item = self.celebrity.celebrities[indexPath.section];
    
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = item.uid;
    [self showViewController:vc sender:nil];
}

#pragma mark - event response
- (void)searchBarBtnTapped:(UIBarButtonItem *)item {
//    KABCosTopicSeaVC *seaVC = [[KABCosTopicSeaVC alloc] init];
//    seaVC.viewType = KABCosTopicSeaVCTypeSearch;
//    seaVC.completeHandle = ^(NSString *topicStr) {
//        [self jumpToTopicList:topicStr];
//    };
//    [self presentViewController:seaVC animated:YES completion:nil];
    KABCosUserSeaVC *seaVC = [[KABCosUserSeaVC alloc] init];
    UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:seaVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    if (![KABModel sharedInstance].userInfo.misc_detail.is_celebrity) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"只有实名认证的用户才能发布Cosplay" message:@"现在立即去实名认证吗" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"认证" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            [self jumpToAuthentication];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
        return;
    }
    
    [self jumpToPublishCosplay];
}

- (void)titleViewButtonTapped:(UIButton *)btn {
    self.filterView.cellBgColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerCosSelBgColor];
    self.filterView.cellMaskColor = [[ThemeManager sharedManager] themeColorWithName:ThemeManagerCosSelTintColor];
    [self.filterView showInView:self.navigationController.navigationBar];
}

#pragma mark - private methods
- (UIButton *)buttonWithTitle:(NSString *)title {
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeSystem];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"cosplay_arrow_down"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(titleViewButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
    [btn sizeToFit];
    [btn layoutButtonWithEdgeInsetsStyle:ButtonEdgeInsetsStyleImageRight imageTitlespace:8.0];
    return btn;
}
- (void)jumpToPublishCosplay {
    KABCosplayPublishVC *pubVC = [[KABCosplayPublishVC alloc] init];
    pubVC.completeHandle = ^(){
        [self.tableView.mj_header beginRefreshing];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pubVC];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToAuthentication {
    KABCosAuthenticationVC *vc = [[KABCosAuthenticationVC alloc] init];
    vc.completeHandle = ^(){
        [self jumpToPublishCosplay];
    };
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self presentViewController:nav animated:YES completion:nil];
}
- (void)jumpToTopicList:(NSString *)topic {
    KABMineColCosVC *vc = [[KABMineColCosVC alloc] init];
    vc.viewType = KABMineColCosVCTypeTopicList;
    vc.topicStr = topic;
    [self showViewController:vc sender:nil];
}
- (void)jumpToAtUserHp:(NSString *)atUser {
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_name = atUser;
    [self showViewController:vc sender:nil];
}

- (void)refreshWholeView {
    // 尾部加载更多的显示
    BOOL end;
    if (self.viewType == CosplayViewTypeCelebrity) {
        end = self.celebrity.totalLoad;
    } else {
        end = self.cosplayList.totalLoad;
    }
    
    if (end) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    // 刷新tableView
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    if (self.viewType == CosplayViewTypeCelebrity) {
        [self requestCelebrityWithHeader:isHeader];
    } else {
        [self requestCosplayListWithHeader:isHeader];
    }
    
    // 刷新的时候，刷新一下是否有评论、点赞
    if (isHeader) {
        [self requestCosLikeAndCommentCnt];
    }
}

- (void)cosplayListWithDictionary:(NSDictionary *)dic isHeader:(BOOL)isHeader {
    switch (self.viewType) {
        case CosplayViewTyepWhole:
            [[KABModel sharedInstance] cosplayListWholeWithDictionary:dic isAddMore:!isHeader];
            break;
        case CosplayViewTyepRecommend:
            [[KABModel sharedInstance] cosplayListRecommendWithDictionary:dic isAddMore:!isHeader];
            break;
        case CosplayViewTyepFollow:
            [[KABModel sharedInstance] cosplayListFollowWithDictionary:dic isAddMore:!isHeader];
            break;
        default:
            break;
    }
}

#pragma mark - network request
- (void)requestCosShieldWithCosId:(NSInteger)cosId successHandle:(void(^)(void))success {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId)};
    NSLog(@"屏蔽的请求%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayShield] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay屏蔽返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            if (success) {
                success();
            }
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosPraiseWithCosId:(NSInteger)cosId isPraise:(BOOL)isPraise {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_praise" : isPraise ? @(1) : @(0)};
    NSLog(@"点赞的请求%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayPraise] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay点赞返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay点赞失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosCollectWithCosId:(NSInteger)cosId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosplayListWithHeader:(BOOL)isHeader {
    NSInteger lastId = isHeader ? 0 : self.cosplayList.cosplay_list.lastObject.cosplayId;
    
    NSArray<NSNumber *> *type = @[@(0), @(2), @(1)];
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(lastId) forKey:@"last_id"];
    [pars setObject:@(kRequestCosplayListSize) forKey:@"size"];
    [pars setObject:type[self.viewType] forKey:@"type"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCosplayList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self cosplayListWithDictionary:responseObject isHeader:isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCelebrityWithHeader:(BOOL)isHeader {
    NSInteger startIndex = isHeader ? 0 : self.celebrity.celebrities.count;
    NSDictionary *pars = @{@"index" : @(startIndex),
                           @"size" : @(kRequestCelebirtySize)};
    NSLog(@"请求名人榜的参数：%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiCelebrityList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求名人榜返回：%@", responseObject);
        //        NSLog(@"请求名人榜返回：%@", @"dfdfdf");
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] cosplayCelebrityWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求名人榜失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosLikeAndCommentCnt {
    // 获取未读消息(点赞、评论、回复)的数量(由于存在游客模式，所以这里可以不登录)
    if (![KABModel sharedInstance].isLogin) {
        return;
    }
    
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token};
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiNewMessage] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求未读消息返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [[KABModel sharedInstance] mineNewMsgWithDictionary:responseObject];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求未读消息失败：%@", error);
    }];
}

#pragma mark - getters and setters
- (UIBarButtonItem *)publishBarBtnItem {
    if (!_publishBarBtnItem) {
        _publishBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cosplay_publish"] style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
    }
    return _publishBarBtnItem;
}

- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

- (XDFilterView *)filterView {
    if (!_filterView) {
        _filterView = [[XDFilterView alloc] initWithTitles:self.titlesArray delegate:self];
        _filterView.selectedIndex = self.viewType;
    }
    return _filterView;
}

- (void)setViewType:(CosplayViewTyep)viewType {
    _viewType = viewType;
    NSArray *array = @[@"Cosplay", @"推荐", @"关注", @"名人榜"];
    self.navigationItem.titleView = [self buttonWithTitle:array[viewType]];
}

- (NSArray *)titlesArray {
    if (!_titlesArray) {
        _titlesArray = @[@"全部", @"推荐", @"关注", @"名人榜"];
    }
    return _titlesArray;
}

- (KABCosplayModel *)cosplayList {
    switch (self.viewType) {
        case CosplayViewTyepWhole:
            return [KABModel sharedInstance].cosplayListWhole;
            break;
        case CosplayViewTyepRecommend:
            return [KABModel sharedInstance].cosplayListRecommend;
            break;
        case CosplayViewTyepFollow:
            return [KABModel sharedInstance].cosplayListFollow;
            break;
        default:
            break;
    }
    return nil;
}

- (KABCosplayCelebrity *)celebrity {
    return [KABModel sharedInstance].cosplayCelebrity;
}

@end
